import { APP_NAME } from '../constants';
import { del, get, post, put } from '../utils/http';
import { getPlayServiceToken } from '@/utils/Integrity';

export const userAPI = {
  device_login: async (params: User.QueryParams, signal?: AbortSignal) => {
    const deviceToken = await getPlayServiceToken();
    try {
      const res = await post<User.TokenInfoRes>(
        '/turing-user-center/v1/auth/device-login',
        { ...params },
        {
          signal,
          headers: {
            'ts-user-device-token': deviceToken,
          },
        },
      );
      return res.data;
    } catch (error) {
      console.error('login failed:', error);
      throw new Error('login failed');
    }
  },
  refresh_token: async (params: User.RefreshTokenParams, signal?: AbortSignal) => {
    try {
      const res = await post<User.TokenInfoRes>('/turing-user-center/v1/auth/login', { ...params }, { signal });
      console.log('refresh_token:', res);
      return res.data.data;
    } catch (error) {
      console.error('refresh_token failed:', error);
      throw new Error('refresh_token failed');
    }
  },
  // 手机号-验证码登录
  auth_login: async (params: User.LoginParams) => {
    try {
      const res = await post<User.TokenInfoRes>('/turing-user-center/v1/auth/login', { ...params });
      return res.data;
    } catch (error: unknown) {
      console.error('login failed:', error);
      throw new Error((error as { msg: string })?.msg ?? '');
    }
  },
  // 获取用户信息
  get_user_info: async (userId: string) => {
    try {
      const res = await get<User.UserBaseInfoRes>(`/turing-user-center/v1/users/${userId}`, undefined, {
        'ts-app-name': APP_NAME,
      });
      return res.data;
    } catch (error) {
      console.error('Obtain user information failed:', error);
      throw new Error('Obtain user information failed');
    }
  },
  // 用户注销
  delete_user: async (): Promise<void> => {
    try {
      await del('/turing-user-center/v1/users/logoff');
    } catch (error) {
      console.error('User logoff failed:', error);
      throw new Error('User logoff failed');
    }
  },
  // 更新用户token (用于通知功能)
  update_token: async (params: User.UpdateTokenParams) => {
    try {
      return await put<User.UpdateTokenRes>('/turing-user-center/v1/users/push/token', params);
    } catch (error) {
      console.error('update token failed:', error);
      throw new Error('update token failed');
    }
  },
  //   分配给用户付费墙和内购产品Code的信息
  get_user_products: async () => {
    try {
      const res = await get<User.UserPaywallAssignResponse>(`/turing-user-center/v1/users/product/list`);
      return res.data;
    } catch (error) {
      console.error('Obtain user products failed:', error);
      throw new Error('Obtain user products failed');
    }
  },
};
